<template>
    <div class="container">
      <Breadcrumb :items="['数据分析',  '社会服务办理质效情况']" />
      <a-card class="general-card" style="padding-top:5px">
        <a-row>
        <a-col :flex="1">
          <a-form :model="formModel" label-align="right">
            <a-row :gutter="16">
              <a-space direction="horizontal" :size="5">
                <a-form-item field="areaName" label-col-flex="80px" label="统计县市区">
                  <a-select v-model="formModel.areaName.value" :style="{ width: '150px' }" allow-clear
                    placeholder="全部"
                    :trigger-props="{ autoFitPopupMinWidth: true }">
                    <a-option value="市本级">市本级</a-option>
                    <a-option value="黄州区">黄州区</a-option>
                    <a-option value="团风县">团风县</a-option>
                    <a-option value="红安县">红安县</a-option>
                    <a-option value="麻城市">麻城市</a-option>
                    <a-option value="罗田县">罗田县</a-option>
                    <a-option value="英山县">英山县</a-option>
                    <a-option value="浠水县">浠水县</a-option>
                    <a-option value="蕲春县">蕲春县</a-option>
                    <a-option value="武穴市">武穴市</a-option>
                    <a-option value="黄梅县">黄梅县</a-option>
                  </a-select>
                </a-form-item>
                <a-form-item field="quarter" label-col-flex="80px"
                  label="时间范围">
                  <a-range-picker
                    v-model="formModel.dateRange.value"
                    mode="date"
                    style="width: 254px;"
                  />
                </a-form-item>
                <a-form-item field="isGrowth" label-col-flex="120px"
                  label="是否查询区间新增">
                  <a-select v-model="formModel.isGrowth.value" style="width: 74px;">
                    <a-option :value="true">是</a-option>
                    <a-option :value="false">否</a-option>
                  </a-select>
                </a-form-item>
                <a-form-item field="quarter" label-col-flex="100px"
                  label="统计截止日期">
                  <a-input
                    v-model="formModel.endTime.value"
                    readonly
                    disabled
                    style="width: 150px;"
                  />
                </a-form-item>
                <a-form-item label-col-flex="0px" label="">
                  <a-space direction="horizontal" :size="12">
                    <a-button @click="fetchData">
                      <template #icon>
                        <icon-search />
                      </template>
                      查询
                    </a-button>
                    
                    <a-button @click="downAll">
                      <template #icon>
                          <icon-download />
                      </template>
                      导出
                  </a-button>
                  </a-space>
                </a-form-item>
              </a-space>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
        <a-table :data="renderData" :columns="columns" sticky-header :pagination="false" page-position="bl" :bordered="{cell:true}" :summary="summary" :summary-span-method="spanMethod" :scrollbar="true"
          :scroll="{ x: '100%', y: '700px' }">
          <template #summary-cell="{ column, record, rowIndex }">
            <span>{{ record[column.dataIndex] }}</span>
          </template>
        </a-table> 
      </a-card>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick } from 'vue';
  import { useRouter } from 'vue-router';
  import { Modal, Message } from '@arco-design/web-vue';
  import { postRequest, uploadFileRequest } from '@/api/common';
  import { formatSortByDepart } from '@/utils/sortUtil.js';
  import { baseURL } from '@/api/base';

  const downAll = ()=>{
    let startTime = "";
    let endTime = "";
    if(formModel.dateRange.value!=null && formModel.dateRange.value.length>1){
      startTime = formModel.dateRange.value[0];
      endTime = formModel.dateRange.value[1];
    }
    window.location.href = baseURL + 'dsms/ihgDataProcess/downSocialStaticData?isGrowth='+
    formModel.isGrowth.value + "&startTime="+startTime+"&endTime="+endTime;
  }

  const router = useRouter();
  const formModel = {
    areaName: ref(""),
    endTime: ref(""),
    dateRange: ref<any[]>([]),
      isGrowth:ref(false),
  };
  const renderData = ref<any[]>([]);
  const endTimeList = ref<any[]>([]);
  const columns:any = reactive([
    {
      title: '序号',
      dataIndex:'index',
      align: 'center',
      fixed: 'left',
      width: 60,
    },
    {
      title: '部门',
      dataIndex:'departmentName',
      align: 'center',
      fixed: 'left',
      width: 120,
    },
    {
      title: '板块名称',
      dataIndex:'moduleName',
      align: 'center',
      width: 120,
    },
    {
      title: '服务项目',
      dataIndex:'projectName',
      align: 'center',
      width: 120,
    },
    {
      title: '社会服务',
      dataIndex: 'health',
      align: 'center',
      width: 480,
      children:[{
        title: '业务量',
        dataIndex: 'socialOrderCountSum',
        align: 'center',
        sortable: {sortDirections: ['ascend', 'descend']},
        width: 120,
      },{
        title: '进驻市场主体数量',
        dataIndex: 'socialEnterMarketCountSum',
        sortable: {sortDirections: ['ascend', 'descend']},
        align: 'center',
        width: 120,
      },{
        title: '上线服务或产品数',
        dataIndex: 'socialOnlineServiceCountSum',
        align: 'center',
        sortable: {sortDirections: ['ascend', 'descend']},
        width: 120,
      },{
        title: '涉及资金（万元）',
        dataIndex: 'socialInvolveMoneySum',
        align: 'center',
        sortable: {sortDirections: ['ascend', 'descend']},
        width: 120,
      }]  
    },
    // {
    //   title: '统计截止日期',
    //   dataIndex: 'createdTime',
    //   align: 'center',
    //   width: 120,
    // }
  ]);
  
  let sumData = reactive({
    index: '合计',
    moduleName: '',
    projectName: '',
    governmentIhgOrderCount: 0,
    socialInvolveMoneySum: 0 as any,
    socialOrderCountSum: 0,
    socialEnterMarketCountSum: 0,
    socialOnlineServiceCountSum: 0,
    governmentOnlinePercent: 0,
    governmentAllOrderCount: 0
  })
  const summary = () => {
    return [sumData]
  }
  
const spanMethod = ({rowIndex, columnIndex}) =>{
  if(rowIndex == 0 && columnIndex == 0){
    return {
        colspan: 4
      }
  }
}

  // 修改fetchData函数，直接使用静态数据
  const fetchData = async() => {
  let startTime = "";
  let endTime = "";
    if(formModel.dateRange.value!=null && formModel.dateRange.value.length>1){
      startTime = formModel.dateRange.value[0];
      endTime = formModel.dateRange.value[1];
    }
    sumData = {
      index: '合计',
      moduleName: '',
      projectName: '',
      governmentIhgOrderCount: 0,
      socialInvolveMoneySum: 0 as any,
      socialOrderCountSum: 0,
      socialEnterMarketCountSum: 0,
      socialOnlineServiceCountSum: 0,
      governmentOnlinePercent: 0,
      governmentAllOrderCount: 0
    }
    // const [startDate, endDate] = formModel.dateArea.value.map(date => date ? date.format('YYYY-MM-DD') : '');
    let res = await postRequest("dsms/ihgDataProcess/querySocialStatistical", {
      areaName: formModel.areaName.value,
      isGrowth: formModel.isGrowth.value,
      startTime: startTime,
      endTime: endTime
    });
    let cEndTime = ""
    // 计算合计行数据
    res.forEach((item: any,index:number) => {
      item.index = index+1;
      sumData.governmentIhgOrderCount = sumData.governmentIhgOrderCount + Number(item.governmentIhgOrderCount);
      sumData.socialInvolveMoneySum = sumData.socialInvolveMoneySum + Number(item.socialInvolveMoneySum);
      sumData.socialOrderCountSum = sumData.socialOrderCountSum + Number(item.socialOrderCountSum);
      sumData.socialEnterMarketCountSum = sumData.socialEnterMarketCountSum + Number(item.socialEnterMarketCountSum);
      sumData.socialOnlineServiceCountSum = sumData.socialOnlineServiceCountSum + Number(item.socialOnlineServiceCountSum);
    });

    let timeRes = await postRequest("/dsms/ihgDataProcess/querySocialLastDay", {
      areaName:formModel.areaName.value,
      startTime: startTime,
      endTime: endTime,
      pageSize:1
    });
    console.log(timeRes);
    if(timeRes.list.length>0){
      let latest = timeRes.list[0].createdTime;
      for (let i = 1; i < timeRes.list.length; i++) {
        if (new Date(timeRes.list[i].createdTime) > new Date(latest)) {
          latest = timeRes.list[i].createdTime;
        }
      }
      console.log(timeRes);
      formModel.endTime.value = latest.substring(0,10);
    }

    sumData.socialInvolveMoneySum = parseFloat(sumData.socialInvolveMoneySum).toFixed(4);
    
    res = formatSortByDepart(res);
    res.forEach((item: any,index: number) => {
      item.index = index+1;
    });
    renderData.value = res;
  };
  
  fetchData();
  </script>
  
  <script lang="ts">
  export default {
    name: 'comprehensive',
  };
  </script>
  
  <style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }
  ::v-deep(.arco-input-wrapper .arco-input[disabled]){
    color: black;
    -webkit-text-fill-color: black;
  }
  </style>